package com.example.demo.leetcode.top100;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _43验证二叉搜索树
 * @description
 * @date 2023/06/16 17:01
 * <p>
 * ******************************************************
 */
public class _43验证二叉搜索树 {

    public boolean isValidBST(TreeNode root) {
        if (root == null) return true;
        return isValid(root, null, null);
    }

    /**
     *
     * @param root
     * @param max 左子树的最大节点
     * @param min 右子树的最小节点
     * @return
     */
    private boolean isValid(TreeNode root, TreeNode max, TreeNode min) {
        if (root == null) {
            return true;
        }
        if (max != null && root.val <= max.val) return false;
        if (min != null && root.val >= min.val) return false;
        return isValid(root.left, max, root) && isValid(root.right, root, min);
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
